package co.edu.unal.satacredito.administration.view.brand;

import java.util.Map;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;
import co.edu.unal.satacredito.administration.view.general.AdministrationBean;
import co.edu.unal.satacredito.infrastructure.dto.BrandDTO;
import co.edu.unal.satacredito.mediation.BrandEJBLocal;

@ManagedBean(name = "edit_Brands")
public class EditBrand extends AdministrationBean {

	@EJB
	BrandEJBLocal brandEJB;
	
	private String brandId;
	private BrandDTO brandDTO;

	@PostConstruct
	public void init() {
		if (brandDTO == null) {
			brandDTO = new BrandDTO();
		}
	}
	
	public String loadCreate(){
		brandDTO.setId(null);
		return SUCCESS;
	}

	public String loadEdit() {
		Map<String, String> params = FacesContext.getCurrentInstance()
				.getExternalContext().getRequestParameterMap();
		
		brandId = params.get("brandid");
		brandDTO.setId(brandId);
		try {
			brandDTO = brandEJB.findBrand(brandId);
			return SUCCESS;
		} catch (Exception e) {
			FacesContext facesContext = FacesContext.getCurrentInstance();
			facesContext.addMessage(null, new FacesMessage(
					"Lo sentimos ocurrio un error inesperado"));
			return FAILED;
		}
	}
	
	public String doCreate(){
		try {			
			brandEJB.create(brandDTO);
			
			FacesContext facesContext = FacesContext.getCurrentInstance();
			facesContext.addMessage(null, new FacesMessage(
					"Nueva marca creada"));
			
			return SUCCESS;
			
		} catch (Exception e) {
			FacesContext facesContext = FacesContext.getCurrentInstance();
			facesContext.addMessage(null, new FacesMessage(
					"Error al crear la marca"));
			
			return FAILED;
		}
		
	}

	public String doEdit() {
		try {
			brandEJB.edit(brandDTO.getId(),brandDTO);
			
			FacesContext facesContext = FacesContext.getCurrentInstance();
			facesContext.addMessage(null, new FacesMessage(
					"Actualización finalizada"));
			return SUCCESS;
			
		} catch (Exception e) {
			FacesContext facesContext = FacesContext.getCurrentInstance();
			facesContext.addMessage(null, new FacesMessage(
					"La marca no se pudo actualizar"));
			return FAILED;
		}
	}
	
	public String doDelete(){
		try {
			
			brandEJB.delete(brandDTO.getId());
			
			FacesContext facesContext = FacesContext.getCurrentInstance();
			facesContext.addMessage(null, new FacesMessage(
					"La marca a sido borrada"));
			return SUCCESS;
			
		} catch (Exception e) {
			FacesContext facesContext = FacesContext.getCurrentInstance();
			facesContext.addMessage(null, new FacesMessage(
					"No se pudo borrar la Marca"));
			
			return FAILED;
		}
	}
	
	public String cancel(){
		return SUCCESS;
	}

	public BrandDTO getBrandDTO() {
		return brandDTO;
	}

}
